'''#urllib 来实现有道翻译
from urllib import request,parse
import json

def fanyi(keyword):
    base_url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    # 构建请求对象
    data = {
        'i' : keyword,
        'doctype' : 'json'
    }
    data = parse.urlencode(data)

    headers = {
        'Content-Length':len(data),
        'User - Agent': 'Mozilla / 5.0(Windows NT 10.0;WOW64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 63.0.3239.26Safari / 537.36Core / 1.63.6735.400QQBrowser / 10.2.2328.400'
    }

    req = request.Request(url=base_url,data=bytes(data,encoding='utf-8'),headers=headers)
    res = request.urlopen(req)

    str_json = res.read().decode('utf-8')  # 获取响应的json字串

    myjson = json.loads(str_json) # 把json转字典
    info = myjson['translateResult'][0][0]
    print(info)
    #print(myjson)

if __name__ == '__main__':
    while True:
        keyword = input('输入翻译的单词：')
        if keyword == 'q':
            break
        fanyi(keyword)
'''
#使用request 实现有道翻译的爬取
import requests
import json

def fanyi(keyword):
    base_url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    # 构建请求对象
    data = {
        'i' : keyword,
        'doctype' : 'json'
    }

    res = requests.post(base_url,data=data)

    str_json = res.content.decode('utf-8')  # 获取响应的json字串

    myjson = json.loads(str_json) # 把json转字典
    # print(myjson)
    # {'type': 'EN2ZH_CN', 'errorCode': 0, 'elapsedTime': 1, 'translateResult': [[{'src': 'python', 'tgt': 'python'}]]}
    info = myjson['translateResult'][0][0]
    print(info)

if __name__ == '__main__':
    while True:
        keyword = input('输入翻译的单词：')
        if keyword == 'q':
            break
        fanyi(keyword)